package com.scalar.chiptrack.jasper.base.datasource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
import java.util.*;

/**
 * User: sujan
 * Date: Feb 23, 2011
 * Time: 7:43:56 PM
 */
public final class JasperDataSourceFactory {

	private JasperDataSourceFactory() {
	}

	public static ChiptrackJasperDataSource getDataSource(ResultSet rset) throws SQLException {
		return new MapCollectionDataSource(convertToMapCollection(rset));
	}

	private static Collection convertToMapCollection(ResultSet rset) throws SQLException {
		List<Map<String, Object>> mapCollection = new ArrayList<Map<String, Object>>();
		if (rset != null) {
			ResultSetMetaData metadata = rset.getMetaData();
			int colCount = metadata.getColumnCount();
			List<String> columnNames = new ArrayList<String>();
			for (int i = 1; i <= colCount; i++) {
				columnNames.add(metadata.getColumnName(i));
			}
			while (rset.next()) {
				Map<String, Object> row = new HashMap<String, Object>();
				for (int i = 1; i <= colCount; i++) {
					row.put(columnNames.get(i-1), rset.getObject(i));
				}
				mapCollection.add(row);
			}
		}

		return mapCollection;
	}
}
